package com.qf.limit.commons.exception;


import com.qf.limit.commons.r.Codes;
import com.qf.limit.commons.r.R;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.validation.ConstraintViolationException;
import java.util.List;
import java.util.stream.Collectors;

@RestControllerAdvice
public class GlobalExceptionHandler {
    /**
     * 全局异常处理
     * Throwable
     *      Exception
     *      Error
     * @param e
     * @return
     */
    @ExceptionHandler(Throwable.class)
    public R globalExceptionHandler(Throwable e){
        System.out.println("捕获到全局异常信息！！"+e);
        return R.fail(Codes.FAIL);
    }

    /**
     * 自定义的业务层异常
     * @param e
     * @return
     */
    @ExceptionHandler(ServiceException.class)
    public R serviceException(ServiceException e){
        Codes codes = e.getCodes();
        return R.fail(codes);
    }

    /**
     * 参数校验异常
     * @param e
     * @return
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public R requestBodyParamException(MethodArgumentNotValidException e){
        //Stream流
        List<String> errors = e.getBindingResult().getAllErrors()
                .stream()
                .map(objectError -> objectError.getDefaultMessage())
                .collect(Collectors.toList());
        return R.fail(Codes.PARAMS_ERROR, errors);
    }

    @ExceptionHandler(ConstraintViolationException.class)
    public R paramsValidateException(ConstraintViolationException e){
        List<String> message = e.getConstraintViolations().stream()
                .map(constraintViolation -> constraintViolation.getMessage())
                .collect(Collectors.toList());
        return R.fail(Codes.PARAMS_ERROR, message);
    }
}
